import os
import subprocess
from typing import Optional, List

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from database import get_db
from schema import command_schema

from services import command_service


import logging
logger = logging.getLogger("fast-run")

from route.user_api import get_current_user

router = APIRouter(tags=["command"],
                   dependencies=[Depends(get_current_user)]  # 🔑 所有路由都需要认证
                   )
@router.get("", response_model=List[command_schema.CommandOut])
def list_commands(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    return command_service.get_all_commands(db, skip, limit)

# 查询单条
@router.get("/{command_id}", response_model=command_schema.CommandOut)
def get_command(command_id: int, db: Session = Depends(get_db)):
    cmd = command_service.get_command_by_id(db, command_id)
    if not cmd:
        raise HTTPException(status_code=404, detail="Command not found")
    return cmd

# 创建
@router.post("", response_model=command_schema.CommandOut)
def create_command(cmd: command_schema.CommandCreate, db: Session = Depends(get_db)):
    return command_service.create_command(db, cmd)

# 更新
@router.put("/{command_id}", response_model=command_schema.CommandOut)
def update_command(command_id: int, cmd: command_schema.CommandUpdate, db: Session = Depends(get_db)):
    updated = command_service.update_command(db, command_id, cmd)
    if not updated:
        raise HTTPException(status_code=404, detail="Command not found")
    return updated

# 删除
@router.delete("/{command_id}")
def delete_command(command_id: int, db: Session = Depends(get_db)):
    success = command_service.delete_command(db, command_id)
    if not success:
        raise HTTPException(status_code=404, detail="Command not found")
    return {"message": "Command deleted successfully"}

# 部署
@router.post("/deploy/{command_id}", response_model=command_schema.CommandOut)
def deploy_command(command_id: int, db: Session = Depends(get_db)):
    cmd = command_service.deploy_command(db, command_id)
    if not cmd:
        raise HTTPException(status_code=404, detail="Command not found")
    return cmd

# 下线
@router.post("/offline/{command_id}", response_model=command_schema.CommandOut)
def offline_command(command_id: int, db: Session = Depends(get_db)):
    cmd = command_service.offline_command(db, command_id)
    if not cmd:
        raise HTTPException(status_code=404, detail="Command not found")
    return cmd